package com.kern.academic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kern.academic.bean.ResponseResult;
import com.kern.academic.bean.enumer.RemoveOperEnum;
import com.kern.academic.entity.XUser;
import com.kern.academic.repository.IUserRepository;
import com.kern.academic.service.IUserService;
import com.kern.academic.util.CommonUtil;
import com.kern.academic.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by caoshi at 9:51 2021-06-26
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserRepository userRepository;

    @Override
    public XUser getByUsernameAndPwd(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }


    @Override
    public ResponseResult listBySearchPage(String search, int pageNum, int pageSize) {
        // 返回结果, 分页用户列表和搜索条件过滤后的用户总数
        ResponseResult result = new ResponseResult();
        Specification<XUser> spec = (Specification<XUser>) (root, query, cb) -> {
            Predicate p1 = cb.like(root.get("username"), "%" + search + "%");
            Predicate p2 = cb.like(root.get("phone"), "%" + search + "%");
            Predicate p3 = cb.like(root.get("email"), "%" + search + "%");
            return cb.or(p1, p2, p3);
        };
        // 默认按创建时间升序排序
        Sort sort = Sort.by(Sort.Direction.ASC, "createtime");
        // 这里的页码pageNum 是从0 开始计数, 也就是第一页的页码是0
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        Page<XUser> userPage = userRepository.findAll(spec, pageable);
        List<XUser> users = userPage.getContent();
        if (users.size() == 0) {
            return ResponseResult.fail("未查询到指定用户");
        }
        long total = userPage.getTotalElements();
        // 转 vo
        List<UserVO> userList = new ArrayList<>();
        users.forEach(user -> {
            UserVO vo = new UserVO();
            vo.buildByXUser(user);
            userList.add(vo);
        });

        JSONObject resdata = new JSONObject();
        resdata.put("users", userList);
        resdata.put("total", total);
        result.setCode(0);
        result.setData(resdata);
        result.setMessage("查询用户成功!");
        return result;
    }

    @Override
    public long getTotal() {
        return userRepository.count();
    }

    @Override
    public XUser update(XUser user) {
        Optional<XUser> op = userRepository.findById(user.getId());
        if (op.isPresent()) {
            XUser dbuser = op.get();
            // 拷贝不为 null 的属性
            CommonUtil.copyPropertiesIgnoreNull(user, dbuser);
            System.out.println(dbuser);
            return userRepository.saveAndFlush(dbuser);
        }
        return null;
    }

    @Override
    public XUser save(XUser user) {
        if (user != null) {
            return userRepository.saveAndFlush(user);
        }
        return null;
    }

    @Override
    public XUser getById(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        Optional<XUser> opt = userRepository.findById(id);
        return opt.orElse(null);
    }

    @Override
    public RemoveOperEnum removeById(String id) {
        if (StringUtils.isEmpty(id))
            return RemoveOperEnum.NECESSARY_PARAMS_NOT_EXIT;
        if (!userRepository.existsById(id))
            return RemoveOperEnum.USER_NOT_EXIT;
        userRepository.deleteById(id);
        return RemoveOperEnum.REMOVE_SUCCESS;
    }
}
